//本js中调用日期的function都在common/js/dateUtil.js中
AnalysisQcTrend = {
    analysisDicChart: null,
    analysisDicTable: null

};

$(function () {
    //病种
    $('#entityType').combobox({
        data: $.parseJSON($("#entityMap").val()),
        valueField: 'value',
        textField: 'text',
        defaultFilter: 6
    });
    //统计粒度
    $('#analysisGrain').combobox({
        data: [
            // {value: "0", text: "天"},
            // {value: "1", text: "周"},
            {value: "2", text: "月"},
            {value: "3", text: "季"},
            {value: "4", text: "年"}
        ],
        valueField: 'value',
        textField: 'text',
        onLoadSuccess: function () {
            $(this).combobox("setValue", "2");
        }
    });
    //科室
    $('#depart').combobox({
        data:$.parseJSON($("#departMap").val()),
        valueField: 'value',
        textField: 'text'
        //onSelect:ManageIndex.departChange
    });
    //院区
    $('#office').combobox({
        data: $.parseJSON($("#officeMap").val()),
        valueField: 'value',
        textField: 'text',
        onSelect: AnalysisQcTrend.officeChange,
        onLoadSuccess: function () {
            var hospId = $('#hospitalId').val();
            if (hospId != "") {
                $(this).combobox("setValue", hospId);
                $(this).combobox('disable');
            } else {
                //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                if (val.length == 2) {//如果就一个院区 加上全部=2
                    $(this).combobox("setValue", val[1].value);
                    AnalysisQcTrend.officeChange(val[1]);
                    $("#oneOffice").val("yes");
                } else {
                    $(this).combobox("setValue", "");
                    $("#oneOffice").val("no");
                }
            }
        }
    });

    $('#startDate').datebox('setValue', getOneYearStartDate());
    $('#endDate').datebox('setValue', getCurrentDate());

    //查询指标配置
    var ajax = new $ax(Sys.backendPath + "/analysis/qcportal/getReportTrendDic", function (data) {
        AnalysisQcTrend.analysisDicChart = data.chart;
        var tableDic = {};
        $.each(data.table, function (index, dic) {
            tableDic[dic.analysisKey2] = dic.analysisStatus == 1 ? true : false;
        });
        AnalysisQcTrend.analysisDicTable = tableDic;
    }, function (data) {
        layer.msg("查询失败!", {icon: 2});
    });
    ajax.setAsync(false);
    ajax.start();


    //查询加载表格的数据
    AnalysisQcTrend.initChartTable();
});

AnalysisQcTrend.officeChange = function (that) {
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function (data) {
        $('#depart').combobox({
            data: data,
            valueField: 'value',
            textField: 'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    }, function (data) {
        layer.msg("查询失败!" + data.responseJSON.message + "!", {icon: 2});
    });
    ajax.set({"hospID": that.value, "id": "depart"});
    ajax.start();
}
/**
 * 查询图和表数据
 */
AnalysisQcTrend.initChartTable = function () {
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/qcportal/selectReportTrendData", function (data) {
        AnalysisQcTrend.drawUpChart(data.chartUPDatas);
        AnalysisQcTrend.drawDeathChart(data.chartDeathAndSurDatas);
        AnalysisQcTrend.drawHosChart(data.chartAverHosDatas);
        AnalysisQcTrend.drawCostChart(data.chartDatas);
        $('#analysisTable').bootstrapTable("destroy");//先销毁原来的表格
        AnalysisQcTrend.drawTable(data.tableDates);
    }, function (data) {
    });
    params.startDate = $('#startDate').datebox('getValue') + " 00:00:00";//开始日期
    params.endDate = $('#endDate').datebox('getValue') + " 23:59:59";//开始日期
    params.analysisGrain = $('#analysisGrain').combobox('getValue');//统计粒度
    params.analysisDesc = $('#analysisDesc').val();//分析类型 全院或科室
    params.office = $("#office").combobox("getValue");
    params.depart = $("#depart").combobox("getValue");
    params.oneOffice = $("#oneOffice").val();
    params.entityType = $("#entityType").combobox("getValue");
    params.doctor = $("#doctor").val();
    params.day = "day";
    // params.tableYear = tableYear;
    ajax.set(params);
    ajax.start();
};

/**
 * 钻取主页蓝色数字详细信息
 */
AnalysisQcTrend.homeKeyDetailTable = function (key, desc, dishDate) {


    //type=1是从顶部蓝色数字传入，type=2表示从下面表格传入，如果是钻取的科室，传area参数暂时定为主治医师Id
    /* var qcYear = $("#qcYear").combobox("getValue");
     var qcMonth = $("#qcMonth").combobox("getValue");*/
    var office = $("#office").combobox("getValue");
    var depart = $("#depart").combobox("getValue");
    var entityType = $("#entityType").combobox("getValue");
    var doctor = $("#doctor").val();
    var href = Sys.backendPath + "/analysis/qcportal/sendPatTrendCase?key=" + key + "&desc=" + encodeURIComponent(desc) + "&office=" + office + "&depart=" + depart + "&dishDate=" + dishDate + "&entityType=" + entityType + "&doctor=" + doctor;
    console.log(href);
    layer.open({
        type: 2,
        title: ['<i class = "fa fa-list-ol"></i>&nbsp;' + desc, 'padding-left:10px'],
        area: ["95%", "95%"],
        scrollbar: false,//为了禁止父页面滚动条滚动
        skin: 'classfyLBStyle layer-ext-hisui',
        content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
    });
    //Sys.addTabPage($.trim(desc), href,true);

}


/**
 * 根据数据画图
 */
AnalysisQcTrend.drawUpChart = function (chartDatas) {
    echarts.init($("#analysisUpChart")[0]).dispose();
    var lines = [];
    var chartDic = AnalysisQcTrend.analysisDicChart;

    lines.push({desc: chartDic[0].analysisName, data: [], code: chartDic[0].analysisKey});
    // $.each(chartDic, function (index, dic) {
    //     lines.push({desc: dic.analysisName, data: [], code: dic.analysisKey});
    // });
    var chartParams = {
        backgroundColor: '#f2f2f2',//背景颜色
        isHorizontal: false,
        yAxisName: '数量',//y轴单位
        formatterFunc: function (params) {
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0; i < params.length; i++) {
                backStr += params[i].marker + params[i].seriesName + "：" + params[i].value + "%<br>";
            }
            return backStr;
        },
        titleShow: false,
        isDataZoom: false,//是否显示缩放
        legendShow: true,
        legendPosition: 'top',
        gridLeft: "20px",
        gridRight: "10px",
        gridTop: "30px",
        gridBottom: "5px",
        rotate: 0,//x轴数据偏移角度
        showLabel: true,
        legend: {
            show: false
        }
    };
    lineChartVte($("#analysisUpChart"), lines, chartDatas, null, null, chartParams);
};
AnalysisQcTrend.drawDeathChart = function (chartDatas) {
    echarts.init($("#analysisDeathChart")[0]).dispose();
    var lines = [];
    var chartDic = AnalysisQcTrend.analysisDicChart;
    for (i=1;i<3;i++){
        lines.push({desc: chartDic[i].analysisName, data: [], code: chartDic[i].analysisKey});
    }

    // $.each(chartDic, function (index, dic) {
    //     lines.push({desc: dic.analysisName, data: [], code: dic.analysisKey});
    // });
    var chartParams = {
        backgroundColor: '#f2f2f2',//背景颜色
        isHorizontal: false,
        yAxisName: '数量',//y轴单位
        formatterFunc: function (params) {
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0; i < params.length; i++) {
                backStr += params[i].marker + params[i].seriesName + "：" + params[i].value + "%<br>";
            }
            return backStr;
        },
        titleShow: false,
        isDataZoom: false,//是否显示缩放
        legendShow: true,
        legendPosition: 'top',
        gridLeft: "20px",
        gridRight: "10px",
        gridTop: "30px",
        gridBottom: "5px",
        rotate: 0,//x轴数据偏移角度
        showLabel: true,
        legend: {
            show: false
        }
    };
    lineChartVte($("#analysisDeathChart"), lines, chartDatas, null, null, chartParams);
};
AnalysisQcTrend.drawHosChart = function (chartDatas) {
    echarts.init($("#analysisHosChart")[0]).dispose();
    var lines = [];
    var chartDic = AnalysisQcTrend.analysisDicChart;
    lines.push({desc: chartDic[3].analysisName, data: [], code: chartDic[3].analysisKey});
    // $.each(chartDic, function (index, dic) {
    //     lines.push({desc: dic.analysisName, data: [], code: dic.analysisKey});
    // });
    var chartParams = {
        backgroundColor: '#f2f2f2',//背景颜色
        isHorizontal: false,
        yAxisName: '天',//y轴单位
        formatterFunc: function (params) {
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0; i < params.length; i++) {
                backStr += params[i].marker + params[i].seriesName + "：" + params[i].value + "<br>";
            }
            return backStr;
        },
        titleShow: false,
        isDataZoom: false,//是否显示缩放
        legendShow: true,
        legendPosition: 'top',
        gridLeft: "20px",
        gridRight: "10px",
        gridTop: "30px",
        gridBottom: "5px",
        rotate: 0,//x轴数据偏移角度
        showLabel: true,
        legend: {
            show: false
        }
    };
    lineChartVte($("#analysisHosChart"), lines, chartDatas, null, null, chartParams);
};
AnalysisQcTrend.drawCostChart = function (chartDatas) {
    echarts.init($("#analysisCostChart")[0]).dispose();
    var lines = [];
    var chartDic = AnalysisQcTrend.analysisDicChart;
    for (i = 4; i < chartDic.length; i++) {
        lines.push({desc: chartDic[i].analysisName, data: [], code: chartDic[i].analysisKey});
    }
    // $.each(chartDic, function (index, dic) {
    //     lines.push({desc: dic.analysisName, data: [], code: dic.analysisKey});
    // });
    var chartParams = {
        backgroundColor: '#f2f2f2',//背景颜色
        isHorizontal: false,
        yAxisName: '元',//y轴单位
        formatterFunc: function (params) {
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0; i < params.length; i++) {
                backStr += params[i].marker + params[i].seriesName + "：" + params[i].value + "<br>";
            }
            return backStr;
        },
        titleShow: false,
        isDataZoom: false,//是否显示缩放
        legendShow: true,
        legendPosition: 'top',
        gridLeft: "20px",
        gridRight: "10px",
        gridTop: "30px",
        gridBottom: "5px",
        rotate: 0,//x轴数据偏移角度
        showLabel: true,
        legend: {
            show: false
        }
    };
    lineChartVte($("#analysisCostChart"), lines, chartDatas, null, null, chartParams);
};
/**
 * 根据数据画表
 */
AnalysisQcTrend.drawTable = function (tableDates) {
    this.$table =
        $('#analysisTable').bootstrapTable({
            data: tableDates,

            striped: false,//是否显示行间隔色
            pagination: false,//是否显示分页
            showFooter: true,
            //paginationLoop: false,
            //pageSize : 5,//用于设置每页初始显示的条数
            //pageList :[4],
            //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
            sortName: "disDate",
            sortOrder: 'desc',// desc  asc
            maintainSelected: true,//设为true 为选中的状态
            cache: false,
            search: false, //搜索框
            columns: [
                {
                    title: '出院日期', field: 'dishDate', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return "总计";
                    }
                },
                {
                    title: '患者人数', field: 'consistentNum', align: 'center', valign: 'middle', sortable: true,
                    formatter: function (value, row, index) {
                        return "<a onclick='AnalysisQcTrend.homeKeyDetailTable(&apos;" + "consistentNum" + "&apos;,&apos;" + row.dishDate + "月患者人数" + "&apos;,&apos;" + row.dishDate + "&apos;)'>" + value + "</a>";
                    },
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(1, value, "consistentNum");
                    }
                },
                {
                    title: '上报例数', field: 'reported', align: 'center', valign: 'middle', sortable: true,
                    formatter: function (value, row, index) {
                        return "<a onclick='AnalysisQcTrend.homeKeyDetailTable(&apos;" + "reported" + "&apos;,&apos;" + row.dishDate + "月上报例数" + "&apos;,&apos;" + row.dishDate + "&apos;)'>" + value + "</a>";
                    },
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(1, value, "reported");
                    }
                },
                {
                    title: '上报率', field: 'reportedRate', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(3, value, "reported", "consistentNum");
                    }
                },
                {
                    title: '死亡例数', field: 'deathNum', align: 'center', valign: 'middle', sortable: true,
                    formatter: function (value, row, index) {
                        return "<a onclick='AnalysisQcTrend.homeKeyDetailTable(&apos;" + "deathNum" + "&apos;,&apos;" + row.dishDate + "月死亡例数" + "&apos;,&apos;" + row.dishDate + "&apos;)'>" + value + "</a>";

                    },
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(1, value, "deathNum");
                    }
                },
                {
                    title: '死亡率', field: 'deathRate', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(3, value, "deathNum", "consistentNum");
                    }
                },
                {
                    title: '手术并发症例数', field: 'surgeryNum', align: 'center', valign: 'middle', sortable: true,
                    formatter: function (value, row, index) {
                        return "<a onclick='AnalysisQcTrend.homeKeyDetailTable(&apos;" + "surgeryNum" + "&apos;,&apos;" + row.dishDate + "月手术并发症例数" + "&apos;,&apos;" + row.dishDate + "&apos;)'>" + value + "</a>";

                    },
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(1, value, "surgeryNum");
                    }
                },
                {
                    title: '手术并发症发生率', field: 'surgeryRate', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(3, value, "surgeryRate", "consistentNum");
                    }
                },
                {
                    title: '次均住院日', field: 'averageHosDays', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(2, value, "averageHosDays", "consistentNum");
                    }
                },

                {
                    title: '次均住院费用', field: 'averageHosCost', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(2, value, "averageHosCost", "consistentNum");
                    }
                },
                {
                    title: '平均耗材费', field: 'averageConsumCost', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(2, value, "averageConsumCost", "consistentNum");
                    }
                },
                {
                    title: '平均药费', field: 'averageMedeCost', align: 'center', valign: 'middle', sortable: true,
                    footerFormatter: function (value) {
                        return AnalysisQcTrend.sumFieldValue(2, value, "averageMedeCost", "consistentNum");
                    }
                }
            ],
            onPostHeader: function () {  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                //$(".th-inner").css("font-weight","700");//表头字体加粗
                $("#analysisTable > tbody td").each(function (index) {//鼠标悬浮 显示表格数据
                    $(this).attr("title", $(this).text());
                });
            }
        });
};


/**
 * 导出表格数据
 */
AnalysisQcTrend.exportTable = function () {
    $("#analysisTableHead,#analysisTable,.fixed-table-footer>table").tableExport(
        {
            type: 'xlsx',
            escape: 'false'
        }, $('#startDate').datebox('getValue').replace(/-/g, "") + "～" + $('#endDate').datebox('getValue').replace(/-/g, "") + '上报趋势分析'
    )

};

/**
 * 计算表格最后一列数据和
 */
AnalysisQcTrend.sumFieldValue = function (type, value, nField, dField) {
    var disSum = 0;
    var count = 0;
    for (var i in value) {
        if (type == 2) {
            count += value[i][nField] * value[i][dField] * 1000;
        } else {
            count += value[i][nField] * 1000;
        }
        if (dField != undefined) {
            disSum += value[i][dField] * 1000;
        }

    }
    if (count == 0) {//如果是0返回空
        return "";
    }
    count = count / 1000;
    disSum = disSum / 1000;

    if (type == 1) {
        return count;
    } else if (type == 2) {
        return (count / disSum).toFixed(2);
    } else if (type == 3) {
        var pre = (count / disSum * 100).toFixed(2);
        return pre + "%&nbsp;&nbsp;(" + count + ")";
    } else {
        return count;
    }
};
/**
 * 查询按钮
 */
AnalysisQcTrend.search = function () {
    AnalysisQcTrend.initChartTable();
};

function openCaseDetail(date) {
    var index = layer.open({
        type: 2,
        title: ['<i class = "fa fa-line-chart"></i>&nbsp;触发质控项患者详细数据', 'padding-left:20px'],
        area: ['1300px', '500px'], //宽高
        fix: false, //不固定
        //maxmin: true,
        content: '/analysis/qcportal/to_QcCaseDetail?date=' + date + '&startDate=' + $("#startDate").datebox('getValue') +
            '&endDate=' + $('#endDate').datebox('getValue') + '&depart=' + $("#depart").combobox("getValue") + '&office=' + $("#office").combobox("getValue") +
            '&entityType=' + $("#entityType").combobox("getValue") + '&doctor=' + $("#doctor").val()
    });
}